package com.wswy.wzcx.module.handler

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v4.content.FileProvider
import com.che.libcommon.utils.ToastUtils
import com.tbruyelle.rxpermissions2.RxPermissions
import com.wswy.wzcx.AppContext
import com.wswy.wzcx.BuildConfig
import io.reactivex.SingleObserver
import io.reactivex.disposables.Disposable
import java.io.File

class TakePhotoHandler {

    companion object {
        private const val REQ_FROM_CAMERA = 36 //拍照
    }


    private var currImgFile: File? = null
    private var currCallback:((File)->Unit?)?=null

    fun startCamera(act: FragmentActivity?=null,frag:Fragment?=null,block:((File)->Unit?)?){

        currImgFile = null

        currCallback = block

        val permissions =if (act != null) RxPermissions(act) else RxPermissions(frag!!)

        permissions.request(Manifest.permission.CAMERA)
                .singleOrError()
                .subscribe(object : SingleObserver<Boolean> {

                    override fun onSubscribe(d: Disposable) {

                    }

                    override fun onSuccess(aBoolean: Boolean) {
                        if (aBoolean) {

                            val file = generateFile()

                            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                            var contentUri: Uri? = null
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                                contentUri = FileProvider.getUriForFile(AppContext.getContext(), BuildConfig.APPLICATION_ID + ".fileprovider", file)
                            } else {
                                contentUri = Uri.fromFile(file)
                            }

                            try {
                                intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, contentUri)

                                act?.startActivityForResult(intent, REQ_FROM_CAMERA)
                                frag?.startActivityForResult(intent, REQ_FROM_CAMERA)

                                currImgFile = file
                            } catch (e: Exception) {
                                ToastUtils.showText("打开相机失败")
                            }
                        }else{
                            ToastUtils.showText("没有权限")
                        }

                    }

                    override fun onError(e: Throwable) {
                        ToastUtils.showText(e.message)
                    }
                })


    }


    fun handleActivityResult( requestCode:Int,  resultCode:Int,  data:Intent?){
        if (resultCode == Activity.RESULT_OK && requestCode == REQ_FROM_CAMERA){

            currImgFile?.run {

                if (exists() && length() > 0){

                    currCallback?.invoke(this)
                }
            }

        }
    }



    private fun generateFile(): File {
        return File(AppContext.getContext().getExternalFilesDir("photo"), "IMG_" + System.currentTimeMillis() + "_.jpg")
    }

}